package com.ada.config;

import com.ada.pojo.Configuration;
import com.ada.pojo.MappedStatement;
import com.ada.sqlSession.OperationType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Locale;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
//        List<Element> list = rootElement.selectNodes("//select");
        List<Element> list = rootElement.elements();//取出所有子节点
        String namespace = rootElement.attributeValue("namespace");
        for (Element element : list) {
            //通过xml标签名获取到对应的操作，保存到MapperStatement里,从而在执行操作时候，可以通过该sql操作得到对应的执行方法
            OperationType operationType = OperationType.valueOf(element.getName().toUpperCase(Locale.ENGLISH));
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            paramterType= configuration.getTypeRegisters().parseClass(paramterType);
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setOperationType(operationType);
            String key = namespace + "." + id;//sql的唯一标识:namespace.id
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
